package com.kefu.chat.controller;

import cn.hutool.core.util.StrUtil;
import com.kefu.basic.util.IpAddressUtil;
import com.kefu.basic.util.IpCityUtil;
import com.kefu.basic.util.ResponseUtil;
import com.kefu.chat.model.ChatEvaluate;
import com.kefu.chat.model.ChatLeaveMsg;
import com.kefu.chat.service.*;
import com.kefu.chat.util.ChatConstant;
import com.kefu.chat.vo.*;
import com.kefu.chat.vo.ChatUserParam.*;
import com.kefu.common.controller.AbstractBaseController;
import com.kefu.common.multipart.MultiPart;
import com.kefu.common.result.Result;
import com.kefu.common.result.ResultGenerator;
import com.kefu.common.util.Assert;
import com.kefu.common.vo.DetailVo;
import com.kefu.framework.config.UploadProperties;
import com.kefu.robot.vo.RobotDocVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "在线用户接口")
@RestController
@RequestMapping("chat/visitor")
public class ChatUserController extends AbstractBaseController {
    @Autowired
    private ChatRobotService chatRobotService;
    @Autowired
    private ChatEvaluateService chatEvaluateService;
    @Autowired
    UploadProperties uploadProperties;
    @Autowired
    private ChatUserService chatUserService;
    @Autowired
    private ChatChannelService chatChannelService;
    @Autowired
    private ChatLeaveMsgService chatLeaveMsgService;


    @PostMapping("/channelInfo")
    @ApiOperation(value = "获取渠道配置")
    public Result<ChatChannelVo> channelInfo(@Validated @RequestBody DetailVo detail) {
        ChatChannelVo chatChannel = chatChannelService.detailById(detail.getId());
        Assert.isNull(chatChannel, "渠道异常！");
        return ResultGenerator.genSuccessResult(chatChannel);
    }

    @PostMapping("/init")
    @ApiOperation(value = "用户初始化")
    public Result<UserInitR> init(@Validated @RequestBody UserInitP param, HttpServletRequest request) {
        logger.info("用户初始化:{}", param);
        if (StrUtil.isBlank(param.getChannelId())) {
            return ResultGenerator.genValidFailResult();
        }
        return ResultGenerator.genSuccessResult(chatUserService.init(request, param));
    }

    @PostMapping("/robotAsk")
    @ApiOperation(value = "咨询机器人")
    public Result<UserRobotAskR> robotAsk(@Validated @RequestBody UserRobotAskP param) {
        logger.info("用户咨询机器人:{}", param);
        if (StrUtil.hasBlank(param.getUserId(), param.getQuestion())) {
            return ResultGenerator.genValidFailResult();
        }
        return ResultGenerator.genSuccessResult(chatRobotService.userRobotAsk(param));
    }

    @PostMapping("/robotTips")
    @ApiOperation(value = "机器人输入提示")
    public Result<List<RobotDocVo>> robotTips(@Validated @RequestBody UserRobotTipsP param) {
        if (StrUtil.hasBlank(param.getUserId(), param.getQuestion())) {
            return ResultGenerator.genValidFailResult();
        }
        return ResultGenerator.genSuccessResult(chatRobotService.robotTips(param));
    }

    @PostMapping("/connect")
    @ApiOperation(value = "转人工")
    public Result<UserConnectR> connect(@Validated @RequestBody UserConnectP param) {
        logger.info("用户转人工:{}", param);
        if (StrUtil.hasBlank(param.getUserId())) {
            return ResultGenerator.genValidFailResult();
        }
        return ResultGenerator.genSuccessResult(chatUserService.connect(param));
    }

    @PostMapping("/sendMsg")
    @ApiOperation(value = "给客服发消息")
    public Result<UserSendMsgR> sendMsg(@Validated @RequestBody UserSendMsgP param) {
        logger.info("给客服发消息:{}", param);
        if (StrUtil.hasBlank(param.getUserId(), param.getMsgContent())) {
            return ResultGenerator.genValidFailResult();
        }
        return ResultGenerator.genSuccessResult(chatUserService.sendMsg(param));
    }

    @PostMapping("/out")
    @ApiOperation(value = "结束会话")
    public Result<String> out(@Validated @RequestBody UserP param) {
        logger.info("用户结束会话:{}", param);
        if (StrUtil.hasBlank(param.getUserId())) {
            return ResultGenerator.genValidFailResult();
        }
        chatUserService.out(param.getUserId(), ChatConstant.out_type_close);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/getEventMsg")
    @ApiOperation(value = "轮询事件消息")
    public Result<UserGetEventMsgR> getEventMsg(@Validated @RequestBody UserGetEventMsgP param) {
        return ResultGenerator.genSuccessResult(chatUserService.getEventMsg(param));
    }

    @PostMapping("/getOfflineMsg")
    @ApiOperation(value = "获取离线消息")
    public Result<UserGetEventMsgR> getOfflineMsg(@Validated @RequestBody UserGetEventMsgP param) {
        return ResultGenerator.genSuccessResult(chatUserService.getOfflineMsg(param));
    }

    @PostMapping("/getSessionMsg")
    @ApiOperation(value = "获取会话消息")
    public Result<List<UserGetSessionMsgR>> getSessionMsg(@Validated @RequestBody UserGetSessionMsgP param) {
        return ResultGenerator.genSuccessResult(chatUserService.getSessionMsg(param));
    }

    @PostMapping("/getHistoryMsg")
    @ApiOperation(value = "获取历史消息")
    public Result<List<UserGetSessionMsgR>> getHistoryMsg(@Validated @RequestBody UserGetHistoryMsgP param) {
        return ResultGenerator.genSuccessResult(chatUserService.getHistoryMsg(param));
    }

    @PostMapping("/evaluate")
    @ApiOperation(value = "满意度评价")
    public Result<String> evaluate(@Validated @RequestBody UserEvaluate param) {
        chatUserService.evaluate(param);
        return ResultGenerator.genSuccessResult();
    }
    
    @PostMapping("/isEvaluate")
    @ApiOperation(value = "满意度评价")
    public Result<Boolean> isEvaluate(@Validated @RequestBody UserEvaluate param) {
    	Boolean isEvaluate= chatUserService.isEvaluate(param);
    	return ResultGenerator.genSuccessResult(isEvaluate);
    }

    @PostMapping("/upload")
    @ApiOperation(value = "文件上传")
    public Result<MultiPart> upload(MultipartFile file, String userId) {
        return ResultGenerator.genSuccessResult(chatUserService.upload(file, userId));
    }

    @PostMapping("/uploadBase64")
    @ApiOperation(value = "base64文件上传")
    public Result<MultiPart> upload(@Validated @RequestBody ChatUserBase64Vo param) {
        return ResultGenerator.genSuccessResult(chatUserService.uploadBase64Image(param));
    }


    @PostMapping("/typing")
    @ApiOperation(value = "正在输入")
    public Result<String> typing(@Validated @RequestBody UserTypingP param) {
        chatUserService.typing(param);
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/testIp")
    @ApiOperation(value = "testIp")
    public Result<Map> testIp(HttpServletRequest request) {
        Map<String, String> map = new HashMap<String, String>();
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        map.put("ipAddr", IpAddressUtil.getIpAddr(request));
        map.put("ipCity", IpCityUtil.getIpCity(IpAddressUtil.getIpAddr(request)));
        return ResultGenerator.genSuccessResult(map);
    }

    @PostMapping("/getEvaluateInfo")
    @ApiOperation(value = "获取评价设置")
    public Result<ChatEvaluate> getEvaluateInfo(@Validated @RequestBody ChatEvaluateSearchVo search) {
        ChatEvaluate evaluate = chatEvaluateService.getChatEvaluate(search);
        return ResultGenerator.genSuccessResult(evaluate);
    }

    @PostMapping("/leaveMsg")
    @ApiOperation(value = "客户留言")
    public Result<String> leaveMsg(@Validated @RequestBody ChatLeaveMsgP param) {
        logger.info("客户留言: {}", param);
        chatUserService.leaveMsg(param);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/getLeaveMsg")
    @ApiOperation(value = "获取客户留言")
    public Result<List<ChatLeaveMsg>> getLeaveMsg(@Validated @RequestBody UserP param) {
        List<ChatLeaveMsg> list = chatLeaveMsgService.leaveMsgList(param);
        return ResultGenerator.genSuccessResult(list);
    }

    @PostMapping("/submitUserForm")
    @ApiOperation(value = "提交询前表单")
    public Result<String> submitUserForm(@Validated @RequestBody SubmitUserFormP param) {
        logger.info("提交询前表单: {}", param);
        chatUserService.submitUserForm(param);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/beforeUnload")
    @ApiOperation(value = "即将离开页面")
    public void beforeUnload(@Validated @RequestBody UserP param , HttpServletResponse response) {
        logger.info("即将离开页面: {}", param);
        ResponseUtil.responseSuccess(response);
        chatUserService.beforeUnload(param);
    }

    @PostMapping("/getRobotDoc")
    @ApiOperation(value = "获取词条内容")
    public Result<GetRobotDocR> getRobotDoc(@Validated @RequestBody GetRobotDocP param) {
        logger.info("获取词条内容: {}", param);
        return ResultGenerator.genSuccessResult(chatUserService.getRobotDoc(param));
    }

    @PostMapping("/msgComplete")
    @ApiOperation(value = "消息已读")
    public Result<String> msgComplete(@Validated @RequestBody UserP param) {
        chatUserService.msgComplete(param);
        return ResultGenerator.genSuccessResult();
    }
    
    @PostMapping("/changeUser")
    @ApiOperation(value = "修改客户信息")
    public Result<UserInitR> changeUser(@Validated @RequestBody UserChangeP param, HttpServletRequest request) {
    	logger.info("修改客户信息:{}", param);
    	 
    	return ResultGenerator.genSuccessResult(chatUserService.changeUser(request, param));
    }

    @PostMapping("/getVideoToken")
    @ApiOperation(value = "客户请求视频token")
    public Result<GetTokenResult> getVideoToken(@Validated @RequestBody UserP param) {
        GetTokenResult result = chatUserService.getVideoToken(param);
        return ResultGenerator.genSuccessResult(result);
    }

    @PostMapping("/expireVideoToken")
    @ApiOperation(value = "删除客户视频token")
    public Result<Boolean> expireVideoToken(@Validated @RequestBody ChatRongYunExpireTokenVo vo) {
        Boolean result = chatUserService.expireVideoToken(vo);
        return ResultGenerator.genSuccessResult(result);
    }

    @PostMapping("/userVideoInvitation")
    @ApiOperation(value = "用户邀请客服音视频通话")
    public Result<String> userVideoInvitation(@Validated @RequestBody ChatUserParam.UserVideoInvitation param) {
        chatUserService.inviteVideo(param);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/adminVideoStatus")
    @ApiOperation(value = "查看客服音视频通话状态")
    public Result<Boolean> adminVideoStatus(@Validated @RequestBody ChatAdminParam.AdminUserP param ) {
        boolean result = chatUserService.videoStatus(param);
        return ResultGenerator.genSuccessResult(result);
    }

    @PostMapping("/commentDoc")
    @ApiOperation(value = "词条点评")
    public Result<Boolean> commentDoc(@Validated @RequestBody ChatUserParam.UserCommentDoc param ) {
        boolean result = chatUserService.commentDoc(param);
        return ResultGenerator.genSuccessResult(result);
    }

    @PostMapping("/testPush")
    @ApiOperation(value = "testPush")
    public Result<String> testPush(HttpServletRequest request, @RequestBody Map map) {
        Enumeration<String> headerNames = request.getHeaderNames();
        Map<String,String> requestMap = new HashMap<>();
        while (headerNames.hasMoreElements()){
            String headerName = headerNames.nextElement();
            requestMap.put(headerName ,request.getHeader(headerName));
        }
        Map<String, String[]> parameterMap = request.getParameterMap();
        for (Map.Entry<String,String[]> entry:parameterMap.entrySet()){
            String key = entry.getKey();
            String[] value = entry.getValue();
            requestMap.put(key,StringUtils.join(value));
        }
        logger.info("testPush_json:{},{}",requestMap, map);

        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/sysMsg")
    @ApiOperation(value = "系统消息")
    public Result<String> sysMsg(@Validated @RequestBody UserSysMsgP param) {
        String msgId = chatUserService.sysMsg(param);
        return ResultGenerator.genSuccessResult(msgId);
    }
}
